In this part of Tutorial, we will learn how to make form validations.
Source code: https://github.com/AlphaTechstudios/Forms/tree/Angular_tuto_part_4
Disable Sign Up button when submit
Disable the signup button after submit to avoid registering the same user multiple times with the same email. We will see in the next tutorial how make this check in C# code also.
Actually, let’s make the check in HTML in “sign-up.component.html” file by adding the [disable] directive:
<div class="card-footer">
<button [disabled]="isLoading" class="btn btn-primary mr-2">Sign Up</button>
</div>
In “sign-up.component.ts” file in “onSubmit()” method, add a public property called ” isLoading”.
When user clicks on “SignUp” button, wee initialize the “isLoading” to true.
We process the request and switch result (success or error ), we affect “isLoading” to false.
onSubmit() {
if (this.signUpForm.invalid || this.isLoading) {
return;
}
this.isLoading = true;
this.usersService.registerUser(this.signUpForm.value).subscribe(x => {
this.isLoading = false;
this.router.navigate(["/SignIn"])
},
error => {
this.isLoading = false;
});
}
Adding Validation messages
In sign-up.component.html, for each input field, add validations rules messages.
Every time the value of a form control changes, Angular runs validation and generates either a list of validation errors, which results in an INVALID status, or null, which results in a VALID status.
The *ngIf
on the <div>
element reveals a set of nested message divs
but only if the firstName
is invalid and the control is either dirty
or touched
.
<div *ngIf="signUpData.firstName.invalid && (signUpData.firstName.dirty || signUpData.firstName.touched)" class="alert-danger">
<span>First name is required!</span>
</div>
We can add as many messages as we want according to the business requirements, like validation in Email field or Password :
<div *ngIf="signUpData.email.invalid && (signUpData.email.dirty || signUpData.email.touched)" class="alert-danger">
<span *ngIf="signUpData.email.errors.required">Email is required!</span>
<span *ngIf="signUpData.email.errors.email">Email must be a valid address!</span>
</div>
Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.